<?php

class ProcessingController extends BaseController {

	// Table
	public $table = 'order_product';

	// Eloquent Model
	public $model = 'OrderProduct';

	// Base
	public $base = 'processing';

	// Localization
	public $local = 'en';

	// Language Name
	public $language = 'processing';

	// Breadcrumbs
	public $breadcrumbs = [ ['link' => 'processing' , 'title' => 'Processing'] ];
	
	// Enabled filters
	private $_filters = array();

	// Set List Data - Input, Object
	public function setListData( $data, $object ) {
		// Order, Order Product, Employee, Product and Vendor Details
		$columns = array(
			'order_product.id', 'order_product.ORDER_id',
			'order.created_at AS date_ordered', 'order_product.quantity',
			'order_product.benstore_price', 'order_product.peso', 'order_product.delivery_fee_peso',
			'company.id AS company_id', 'company.code AS company_code', 'company_branch.id AS branch_code',
			'company_branch.name AS branch_name', 'login.firstname', 'login.lastname',
			'order_product.PRODUCT_id', 'product_vendor.product_code AS prod_code',
			'product.name AS prod_name', 'product.voucher', 'product.voucher_description',
			'size.code AS size_code', 'product.srp AS prod_srp', 'size.id AS size_id',
			'vendor.id AS VENDOR_id', 'vendor.name AS vendor_name', 'vendor.code AS vendor_code', 'product_vendor.transfer_price',
			'category.code AS category_code', 'main_category.code AS main_category_code',
			'order_product_option.option_value', 'order_product_option.price AS option_price', 'order_product_option.quantity AS option_quantity'
		);
		$object = $object->leftJoin( 'order_product_option', function ( $op ) {
			$op->on( 'order_product.PRODUCT_id', '=', 'order_product_option.PRODUCT_id' );
			$op->on( 'order_product.ORDER_id', '=', 'order_product_option.ORDER_id' );
			$op->on( 'order_product.ORDER_PRODUCT_OPTION_id', '=', 'order_product_option.ORDER_PRODUCT_OPTION_id' );
		} );
		$object = $this->_queryProcessingItem( $object, $columns );
		
		// Retrieve if Order Product ID exists in current active POs
		$po_orders = PurchaseOrderProduct::poItems()->distinct('ORDER_PRODUCT_id')->lists('ORDER_PRODUCT_id');

		// Has been added to previous POs already?
		if ( !empty($po_orders) )
			$object = $object->whereNotIn('order_product.id', $po_orders);
		
		if( !empty($data['filter_id']) )
			$object = $object->where( 'order_product.id', '=', trim($data['filter_id']) );
		
		if ( !empty($data['filter_vendor']) ) {
			$this->_filters['selected_vendor'] = $vendor_id = trim($data['filter_vendor']);
			$object = $object->where( 'vendor.id', '=',  $vendor_id);
		}
		
		$this->_filters['selected_branch'] = array();
		if ( !empty($data['filter_company']) ) {
			$object = $object->where( 'company_branch.COMPANY_id', '=', trim($data['filter_company']) );
			$this->_filters['selected_company'] = trim($data['filter_company']);
			
			// Has Branch filter?
			if ( !empty($data['filter_branch']) ) {
				// Validate if exists under Company
				$branches = CompanyBranch::where('COMPANY_id', $data['filter_company'])
					->whereIn('id', $data['filter_branch'])->lists('id');
				
				if ( !empty($branches) ) {
					$this->_filters['selected_branch'] = $branches;
					$object = $object->whereIn( 'company_branch.id', $branches );
				}
			}
		}
		
		if ( !empty($data['filter_size']) )
			$object = $object->where( 'order_product.SIZE_id', '=', trim($data['filter_size']) );
		
		// Voucher Filter
		if ( !empty($data['filter_voucher']) ) {
			$voucher = ($data['filter_voucher'] == 2 ) ? 1 : 0; 
			$object = $object->where( 'product.voucher', $voucher );
		}

		if ( !empty($data['filter_ids']) ) {
			$item_ids = preg_split('/\r\n|[\r\n]/', $data['filter_ids']);
			$filtered_item_ids = array_filter(array_unique($item_ids));

			if ( !empty($filtered_item_ids) )
				$object = $object->whereIn( 'order_product.id', $filtered_item_ids );
		}

		if ( !empty($data['filter_order_ids']) ) {
			$order_ids = preg_split('/\r\n|[\r\n]/', $data['filter_order_ids']);
			$filtered_order_ids = array_filter(array_unique($order_ids));

			if ( !empty($filtered_order_ids) )
				$object = $object->whereIn( 'order_product.ORDER_id', $filtered_order_ids );
		}
		
		$dt_format = 'm/d/Y H:i:s';
		
		// Has order date start range filter?
		if ( !empty($data['filter_order_date_from']) && trim($data['filter_order_date_from']) ) {
			$from_date = trim($data['filter_order_date_from']) . ' 00:00:00';
			$from_datetime = DateTime::createFromFormat($dt_format, $from_date);

			// Is start date format valid?
			if ( $from_datetime && ($from_date == $from_datetime->format($dt_format)) ) {
				$order_start_date = $from_datetime->format('Y-m-d H:i:s');
				$object = $object->where( 'order.created_at', '>=', $order_start_date );
			}
		}
		
		// Has order date end range filter?
		if ( !empty($data['filter_order_date_to']) && trim($data['filter_order_date_to']) ) {
			$to_date = trim($data['filter_order_date_to']) . ' 23:59:59';
			$to_datetime = DateTime::createFromFormat($dt_format, $to_date);
		
			// Is end date format valid?
			if ( $to_datetime && ($to_date == $to_datetime->format($dt_format)) ) {
				$order_end_date = $to_datetime->format('Y-m-d H:i:s');

				// Has start date? validate if it's earlier
				if ( (!empty($order_start_date) && 
					 ($to_datetime > $from_datetime)) || empty($order_start_date) ) {
					$object = $object->where( 'order.created_at', '<=', $order_end_date );
				}
			}
		}

		return $object;
	}

	// Add Form Data - Additional Data on form
	public function addFormData( $data, $id=null ) {
		
		return $data;
	}
	
	// Add List Data - Additional Data on List
	public function addListData( $data ) {
		$today = new Datetime('now');
		$data['cur_date'] = $today->format('m/d/Y');
		$data['filters'] = $this->_filters;

		$companies = $this->_queryProcessingItem(OrderProduct::active(),  array('company.id', 'company.name', 'company.platform_name'));
		$vendors = $this->_queryProcessingItem(OrderProduct::active(),  array('vendor.id', 'vendor.name'));
		$sizes = $this->_queryProcessingItem(OrderProduct::active(),  array('size.id', 'size.name'));
		
		// Has selected company?
		if ( !empty($this->_filters['selected_company']) ) {
			$company_id = (int) $this->_filters['selected_company'];
			$vendors = $vendors->where('company.id', $company_id);
			$sizes = $sizes->where('company.id', $company_id);
			$branches = $this->_queryProcessingItem(OrderProduct::active(),  array('company_branch.id', 'company_branch.name'))
				->where( 'company_branch.COMPANY_id', '=' , $company_id )
				->distinct('company_branch.id')->orderBy('company_branch.name')->get();
		
			if ( !empty($branches) ) {
				foreach ( $branches as $branch ) {
					$data['branches'][$branch->id] = ucwords($branch->name);
				}
			}
		}

		// Has selected vendor?
		if ( !empty($this->_filters['selected_vendor']) )
			$company = $companies->where('vendor.id', $this->_filters['selected_vendor']);
		
		$data['sizes'] = array('All Sizes');
		foreach( $sizes->distinct('size.id')->orderBy('size.name')->get() as $size )
			$data['sizes'][$size->id] = ucwords($size->name);
		
		$data['vendors'] = array('All Suppliers');
		foreach( $vendors->distinct('vendor.id')->orderBy('vendor.name')->get() as $vendor )
			$data['vendors'][$vendor->id] = ucwords($vendor->name);
		
		$data['companies'] = array('All Clients');
		foreach( $companies->distinct('company.id')->orderBy('company.name')->get()  as $company ) {
			$company_name = $company->name;
			if ( $company->platform_name )
				$company_name .= ' - ' . $company->platform_name;

			$data['companies'][$company->id] = $company_name;
		}

		return $data;
	}
	
	// Process before storing data
	public function preStore($data) {

		// Updated At Rules
		$this->rules['updated_at'][] = 'required';

		if($data['updated_at'] == '') {
			$this->error['updated_at'][] = 'Please Enter Updated At Field';
		}

		return $data;
	}

	// Process before updating data
	public function preUpdate($data) {

		// Updated At Rules
		$this->rules['updated_at'][] = 'required';

		if($data['updated_at'] == '') {
			$this->error['updated_at'][] = 'Please Enter Updated At Field';
		}
		
		return $data;
	}
	
	/**
	 * Retrieve list of Order Item data per company.
	 * If PO is enabled, separates Extra Large items per Order Item.
	 * @author AngelaMisa 03/04/2015
	 * @param $vendor, $selected_items, $po
	 * @return mixed
	 */
	public function getOrderItems( $selected_items, $vendor, $enable_po = false ) {
		$data = $this->_validateProcessingItem( $selected_items, $vendor );
		
		// Has no valid items and vendor passed?
		if ( empty($data['active_items']) )
			return $data;
		
		$active_items = $data['active_items'];
		$columns = array(
			'vendor.id AS vendor_id', 'vendor.code AS vendor_code', 'company_branch.id AS branch', 'company.code AS company', 'order_product.ORDER_id AS order_id',
			'order_product.id AS id', 'order_product.PRODUCT_id AS prod_id', 'product_vendor.product_code AS prod_model', 'order_product.quantity AS prod_qty',
			'order_product.name AS prod_name', 'product.srp AS prod_srp', 'size.code AS size_code', 'size.id AS size_id',
			'category.code AS category_code', 'main_category.code AS main_category_code', 'product.supplier_delivery', 'product.voucher',
			'order_product_option.option_value', 'order_product_option.price AS option_price', 'order_product_option.quantity AS option_quantity'
		);
		
		// For PO, additional columns
		if ( $enable_po ) {}
		
		$items_with_option = OrderProduct::leftJoin( 'order_product_option', function ( $op ) {
			$op->on( 'order_product.PRODUCT_id', '=', 'order_product_option.PRODUCT_id' );
			$op->on( 'order_product.ORDER_id', '=', 'order_product_option.ORDER_id' );
		} );
		$order_items = $this->_queryProcessingItem( $items_with_option, $columns, $active_items );
		$order_items =  $order_items->where( 'vendor.id', $vendor )->get();
		
		if ( !$order_items ) {
			$data['messages']['error'] = 'Items are invalid.';
			$data['messages']['error_items'] = $active_items;
			return $data;
		}
			
		// Group items by company
		foreach ( $order_items as $item ) {
			$item_id = (string) $item->id;
			$order_id = (int) $item->order_id;
			$product_id = (int) $item->prod_id;
			
			// SKU Format : VendorCode-ProductCode-Option-Value All Caps
			$product_sku = $item->vendor_id . '-' . $item->prod_model;
			if ( !empty($item->option_value) ) {
				$trim_sku = str_replace('-', ' ', trim($item->option_value));
				$product_sku .= strtoupper('-' . str_replace('  ', ' ', $trim_sku));
			}
			
			$data['selected_items'][] = $item_id;
			$data['data_items'][$item->company][$item_id] = array(
				'id'					=> $item_id,
				'order_id'		=> $item->order_id,
				'branch' 			=> $item->branch,
				'company'		=> $item->company,
				'prod_id'			=> $item->prod_id,
				'prod_name'	=> $item->prod_name,
				'prod_model'	=> $item->prod_model,
				'prod_sku'		=> $product_sku,
				'prod_qty'		=> $item->prod_qty,
				'prod_srp'		=> $item->prod_srp,
				'size_code'		=> $item->size_code,
				'size_id'			=> $item->size_id,
				'order_id'		=> $item->order_id,
				'extra_large'	=> $item->supplier_delivery
			);
			
			// Item for PO preview?
			if ( $enable_po ) {
				// Group items by company and product and po delivery info.
				$group_id = $item->company;
				
				// Separate Normal Items Group From Extra Large Group and No Delivery Group.
				// Is extra large?
				if ( !empty($item->supplier_delivery) ) {
					$ship_address = Constant::PO_SHIPPING_HOME;
					$group_id .= '_XL_' . $item_id; 
				}
				// Is Voucher Type or No Delivery Item?
				elseif ( !empty($item->voucher) || ($item->size_id == Constant::PROD_NDEL) ) {
					$ship_address = Constant::PO_SHIPPING_NODELIVERY;
					$group_id .= '_NDEL';
				}
				// Default to Acommerce
				else {
					$ship_address = Constant::PO_SHIPPING_ACOMMERCE;
				}
				
				// New Company group?
				if ( !array_key_exists($group_id, $data['po_items']) )
					$data['po_items'][$group_id] = array('items' => array(), 'total' => 0, 'qty' => 0, 'shipping_address' => '');

				// New Product in Company group
				if ( !array_key_exists($product_sku, $data['po_items'][$group_id]['items']) ) {
					$data['po_items'][$group_id]['items'][$product_sku] = array(
						'prod_id'				=> $product_id,
						'prod_name'		=> $item->prod_name,
						'prod_model'		=> $item->prod_model,
						'prod_sku'			=> $product_sku,
						'prod_srp'			=> $item->prod_srp,
						'size_code'			=> $item->size_code,
						'size_id'				=> $item->size_id,
						'prod_qty'			=> 0,
						'prod_total'			=> 0,
						'option_value'		=> !empty( $item->option_value ) ? $item->option_value : '',
						'option_price'		=> !empty( $item->option_value ) ? number_format( $item->option_price, 2 ) : '',
						'option_qty'		=> 0,
						'option_total'		=> 0,
						'total'					=> 0
					);
				}
				
				// Compute for Products Total Quantity and Total Price with Additionals
				$opt_qty = ( empty($item->option_quantity) ) ? $item->prod_qty : $item->option_quantity;
				$prod_add_price = $item->option_price * $opt_qty;
				$prod_total = $item->prod_qty * $item->prod_srp;
				$item_total = $prod_add_price + $prod_total;

				$data['po_items'][$group_id]['items'][$product_sku]['option_total'] 	+= $prod_add_price;
				$data['po_items'][$group_id]['items'][$product_sku]['total']				+= (float) $item_total;
				$data['po_items'][$group_id]['total']												+= (float) $item_total;
				$data['po_items'][$group_id]['items'][$product_sku]['prod_qty']		+= $item->prod_qty;
				$data['po_items'][$group_id]['items'][$product_sku]['prod_total']		+= $prod_total;
				$data['po_items'][$group_id]['items'][$product_sku]['option_qty']		+= $opt_qty;
				$data['po_items'][$group_id]['qty']													+= $item->prod_qty;

				// Set P. O. Shipping Address
				switch( $ship_address ) {
					case Constant::PO_SHIPPING_ACOMMERCE:
						$order_set = Lang::get('info.ACOMMERCE.address');
						break;
					case Constant::PO_SHIPPING_HOME:
						$order_set = OrderToSet::where(array('ORDER_id'	=> $order_id, 'SET_id'	=> $item->size_id))->first();
						
						// Address Found
						if ( $order_set )
							$data['po_items'][$group_id]['shipping_address'] = $order_set->address;
						break;
					case Constant::PO_SHIPPING_NODELIVERY:
						$data['po_items'][$group_id]['shipping_address'] = 'No Delivery';
						break;
				}
			}
		}
		
		// Save Error Items. Items not found in Processing and Vendor.
		foreach ( $active_items as $val ) {
			if ( !in_array($val, $data['selected_items']) )
				$data['messages']['error_items'][] = $val;
		}

		if ( !empty($data['messages']['error_items']) )
			$data['messages']['error'] = 'Item(s) are invalid.';

		return $data;
	}

	/**
	 * Generates Purchase Order from processing ordered products given.
	 * @author AngelaMisa 02/20/2015
	 * @return mixed
	 */
	public function generatePo() {
		$data = Input::all();
		$result = $this->_validateProcessingItem( $data['items'], $data['vendor_id'] );
		$result['purchase_orders'] = array();
	
		if ( empty($result['active_items']) )
			return $result;

		$columns = array(
			'order_product.id AS ORDER_PRODUCT_id', 'order_product.ORDER_id', 'order_product.quantity',
			'order_product.ORDER_PRODUCT_OPTION_id', 'vendor.code as vendor_code', 'order_product.SIZE_id',
			'company.code AS company_code', 'company_branch.name AS branch_name', 'company_branch.id AS branch_code',
			'order_product.PRODUCT_id', 'product_vendor.product_code AS prod_code', 'product.name AS prod_name',
			'product.srp', 'product_vendor.transfer_price', 'product.voucher', 'product.supplier_delivery'
		);
		$object = $this->_queryProcessingItem( OrderProduct::active(), $columns, $result['active_items'] );
		$object = $object->where( 'vendor.id', $data['vendor_id'] )->get();
			
		if ( !$object->count() ) {
			$result['messages']['error'] = 'Item(s) are Invalid.';
			return $result;
		}
		
		$user = Auth::user();
		$user_id = $user->id;
		$isManagerAction = ( $user->userGroup->level == Constant::USER_MANAGER );
		$items = array();
		$purchase_orders = array();
		$orders = array();
		$result['selected_items'] = array();

		foreach ( $object as $item ) {
			$item_id = (string) $item->ORDER_PRODUCT_id;
			$order_id = (int) $item->ORDER_id;
			$result['selected_items'][] = $item_id;
			$group_id = 'po_' . $item->company_code;
			
			// Separate Normal Items Group From Extra Large Group and No Delivery Group.
			// Is extra large?
			if ( !empty($item->supplier_delivery) ) {
				$ship_address = Constant::PO_SHIPPING_HOME;
				$group_id .= '_XL_' . $item_id;
			}
			// Is Voucher Type?
			elseif ( !empty($item->voucher) ) {
				$ship_address = Constant::PO_SHIPPING_NODELIVERY;
				$group_id .= '_NDEL';
			}
			// Default to Acommerce
			else {
				$ship_address = Constant::PO_SHIPPING_ACOMMERCE;
			}
			
			// Save order id
			if ( !in_array($order_id, $orders) )
				$orders[] = $order_id;
		
			if ( !array_key_exists($group_id, $items) ) {
				$po 									= new PurchaseOrder();
				$po->VENDOR_id 				= $data['vendor_id'];
				$po->company_code 			= $item->company_code;
				$po->shipping_method	 	= $ship_address;
				$po->status 						= Constant::PO_PENDING;
				$po->comment 					= empty($data['comments'][$group_id]) ? '' : $data['comments'][$group_id];
				$po->total_transfer_price 	= 0;
				$po->created_by				= $user_id;
				$po->modified_by				= $user_id;
				$po->status 						= Constant::PO_PENDING;
				
				if ( $isManagerAction ) {
					$po->status = Constant::PO_APPROVED;
					$po->approved_at = DB::raw('CURRENT_TIMESTAMP');
					$po->approved_by = $user_id;
				}
				
				$po->save();
				$purchase_orders[$group_id] = $po_id = $po->id;
				$items[$group_id] = array('total_transfer_price' => 0, 'items' => array());
			}
		
			$items[$group_id]['items'][$item->ORDER_PRODUCT_id] = array(
				'PURCHASE_ORDER_id'	=> $purchase_orders[$group_id],
				'ORDER_PRODUCT_id'		=> $item->ORDER_PRODUCT_id,
				'quantity'							=> $item->quantity,
				'transfer_price'					=> $item->transfer_price,
				'srp'									=> $item->srp
			);
			
			$items[$group_id]['total_transfer_price'] += $item->transfer_price * $item->quantity;
		}
		
		// Save items Per PO
		foreach ( $purchase_orders as $company => $po ) {
			// Company Details
			$company_info = $items[$company];
			
			// Update Total Transfer Price and
			$po = PurchaseOrder::find($po);
			$po->total_transfer_price 	= $company_info['total_transfer_price'];
			$po->save();
		
			// Insert Item Products under P. O.
			PurchaseOrderProduct::insert($company_info['items']);
			
			// Approved PO? Change status to Order From Supplier and email client.
			if ( $isManagerAction ) {
				# API : UPDATE ORDER PRODUCT STATUS FROM PROCESSING TO ORDERED FROM SUPPLIER
				OrderProduct::whereIn('id', array_keys($company_info['items']))->update(array('status' => Constant::ORDER_ORDERED_FROM_SUPPLIER));
				
				// Change status of Order. to Ordered From Supplier when all items have the status. Note: Temporary
				foreach ( $orders as $order ) {
					$order_items = OrderProduct::active()->where('ORDER_id', $order)
						->where('status', '>=', Constant::ORDER_ORDERED_FROM_SUPPLIER)
						->count();
					$all_order_items = OrderProduct::active()->where('ORDER_id', $order)->count();
					
					# API : UPDATE ORDER STATUS FROM PROCESSING TO ORDERED FROM SUPPLIER
					if ( $order_items == $all_order_items )
						Order::active()->where('id', $order)->update(array('status' => Constant::ORDER_ORDERED_FROM_SUPPLIER));
				}
			}
		}

		// Save Error Items. Items not found in Processing and Vendor.
		foreach ( $result['active_items'] as $val ) {
			if ( !in_array($val, $result['selected_items']) )
				$result['messages']['error_items'][] = $val;
		}
		
		if ( !empty($result['messages']['error_items']) )
			$result['messages']['error'] = 'Item(s) are invalid.';
		
		$result['purchase_orders'] = array_values($purchase_orders);
		
		return $result;
	}
	
	/**
	 * Query Processing Order Items. Joined Already with related models.
	 * @author AngelaMisa 03/05/2015
	 * @param $object, $cols, $active_items
	 * @return mixed
	 */
	private function _queryProcessingItem( $object, $cols, array $items = array() ) {
		$object = $object->select( $cols )
			->join( 'order', 'order.id', '=', 'order_product.ORDER_id' )
			->join( 'product', 'order_product.PRODUCT_id', '=', 'product.id' )
			->join( 'company', 'order.COMPANY_id', '=', 'company.id' )
			->join( 'login', 'order.EMPLOYEE_id', '=', 'login.id' )
			->join( 'company_branch', 'login.BRANCH_id', '=', 'company_branch.id')
			->join( 'product_vendor', 'product.id', '=', 'product_vendor.PRODUCT_id' )
			->join( 'vendor', 'product_vendor.VENDOR_id', '=', 'vendor.id' )
			->join( 'size', 'order_product.SIZE_id', '=', 'size.id' )
			->join( 'category', 'order_product.CATEGORY_id', '=', 'category.id')
			->join( 'main_category_category', 'category.id', '=', 'main_category_category.CATEGORY_id' )
			->join( 'main_category', 'main_category_category.MAIN_CATEGORY_id', '=', 'main_category.id' )
			->where( 'order_product.archived', 0 )
			->where( 'order_product.status', Constant::ORDER_PROCESSING )
			->where( 'order.created_at', '<=', DB::raw('CURRENT_TIMESTAMP - INTERVAL 1 DAY') );
	
		if ( !empty($items) )
			$object = $object->whereIn( 'order_product.id', $items );
	
		return $object;
	}
	
	
	/**
	 * Validate and Return given Order Item. If they are valid for P. O.
	 * @author AngelaMisa 03/06/2015 3:07am
	 * @param $selected_items, $vendor
	 * @return mixed
	 */
	private function _validateProcessingItem( $selected_items, $vendor ) {
		$data = array(
			'selected_items'	=> array(),
			'processed_items'	=> array(),
			'data_items'		=> array(),
			'po_items'			=> array(),
			'messages'			=> array()
		);
		$vendor = (int) $vendor;
		$selected_items = array_filter(array_map(function( $val ) {
			return (int) trim($val); }, explode(',', $selected_items )
		));
		
		// Has incomplete details passed?
		if ( empty($selected_items) || empty($vendor) ) {
			$data['messages']['error_items'] = $selected_items;
			$data['messages']['error'] = 'Incomplete reference passed.';
			return $data;
		}

		// Has invalid vendor?
		$vendor = Vendor::where('id', trim($vendor))->first();
		if ( !$vendor ) {
			$data['messages']['error_items'] = $selected_items;
			$data['messages']['error'] = 'Invalid Supplier #' . $vendor. ' passed.';
			return $data;
		}
	
		// Get Order Products under PO Pending and Approved
		$po_orders = PurchaseOrderProduct::poItems( $selected_items )->distinct('ORDER_PRODUCT_id')->lists('ORDER_PRODUCT_id');
	
		// Some items had been processed already?
		if ( $po_orders > 0 ) {
			$data['processed_items'] = $po_orders;
			foreach ( $selected_items as $key => $val ) {
				if ( !in_array( $val, $po_orders ) )
					$data['active_items'][] = $val;
				else
					$data['messages']['error_items'][] = $val;
			}
		} else {
			$data['active_items'] = $selected_items;
		}
	
		// Are all items processed?
		if ( !empty($data['messages']['error_items']) )
			$data['messages']['error'] = 'Item(s) have been processed already.';
		
		return $data;
	}
	
	/**
	 * Retrieve preview list.
	 * @author AngelaMisa 03/12/2015
	 * @return mixed
	 */
	public function getPreviewList( $limit = 5 ) {
		$cols = array(
			'company.name AS company', 'company_branch.name AS branch', 'login.firstname', 'login.lastname',
			'order.id', 'order.created_at', 'order.payment_method', DB::RAW('COUNT(*) AS total_items') ) ;
		
		$data['payment_method'] = Constant::getPaymentList( true );
		$results =  $this->_queryProcessingItem( OrderProduct::active(), $cols );
		
		// Retrieve if Order Product ID exists in current active POs
		$po_orders = PurchaseOrderProduct::poItems()->distinct('ORDER_PRODUCT_id')->lists('ORDER_PRODUCT_id');
		
		// Has items added to previous POs already?
		if ( !empty($po_orders) )
			$results = $results->whereNotIn('order_product.id', $po_orders);
		
		$data['results'] = $results->groupBy('order.id')
			->orderBy( 'order.created_at', 'DESC')->limit(5)
			->get();
		
		return View::make( 'processing-preview-list' )->with( $data );
	}
}